package com.yuwei.base

import android.app.Application
import android.provider.Settings.Global
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.*

abstract class BaseApp: Application() {
    //用于初始化 协程作用域
    private val mInitSDKCoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    private lateinit var mApplicationContext: Application
    override fun onCreate() {
        super.onCreate()
        mApplicationContext = this
        LogUtils.i("BaseApp onCreate了${System.currentTimeMillis()}")
//        asyncInitTask()

    }

    /**
     * 创建线程
     * 创建AsyncTask
     * kotlin协程
     * workManager
     */

    private fun asyncInitTask(){
        mInitSDKCoroutineScope.launch{
            val startTime = System.currentTimeMillis()
            //执行多个任务
            val allResult = listOf(
                async {initMMVK()},
                async {initARouter()},
            )
            val endTime = System.currentTimeMillis()
            //等待所有的初始化任务返回
            val resultList = allResult.awaitAll()
            LogUtils.i("初始化完成,耗时:${endTime - startTime}")
        }
    }
    private suspend fun initMMVK(){
        withContext(Dispatchers.IO){
            MMKV.initialize(mApplicationContext)
            LogUtils.i("MMKV初始化完成,路径为:${MMKV.initialize(mApplicationContext)}")
        }

    }
    private suspend fun initARouter(){
        withContext(Dispatchers.IO){
            if(BuildConfig.DEBUG){
                ARouter.openLog()
                ARouter.openDebug()
            }
            ARouter.init(mApplicationContext)
            LogUtils.i("ARouter初始化完成")
        }
    }

    override fun onTerminate() {
        mInitSDKCoroutineScope.cancel()
        super.onTerminate()

    }
}